<template>
  <div class="app-container">
    <el-card>
      <el-alert
        title="为更好的提供服务，请及时的对订单进行查看和维护以免造成不必要的误会。"
        type="warning"
        show-icon
      />
      <el-form
        :inline="true"
        :model="formOption.data"
        label-width="120px"
        :rules="formOption.rules"
      >
        <!-- 订单搜索 -->
        <el-form-item label="订单搜索：">
          <el-input
            style="width: 240px"
            v-model="formOption.data.orderNo"
            clearable
            placeholder="请输入订单编号进行搜索"
          />
        </el-form-item>

        <!-- 快递单号 -->
        <el-form-item label="快递单号：">
          <el-input
            style="width: 240px"
            v-model="formOption.data.expressNo"
            clearable
            placeholder="请输入快递单号进行搜索"
          />
        </el-form-item>

        <!-- 下单时间 -->
        <el-form-item label="下单时间：">
          <el-date-picker
            type="datetimerange"
            v-model="formOption.data.time"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            range-separator="至"
            clearable
          />
        </el-form-item>

        <!-- 订单状态 -->
        <el-form-item label="订单状态：">
          <el-select v-model="formOption.data.status" clearable placeholder="请选择订单状态">
            <el-option
              v-for="(item, index) in orderStatusList"
              :key="index"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 订单类型 -->
        <el-form-item label="订单类型：">
          <el-select v-model="formOption.data.orderSource" clearable placeholder="请选择订单类型">
            <el-option
              v-for="(item, index) in ORDER_TYPE"
              :key="index"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 客户信息 -->
        <el-form-item label="客户信息：">
          <el-input
            style="width: 240px"
            v-model="formOption.data.userInfo"
            placeholder="请输入收货人姓名或者手机号"
          />
        </el-form-item>

        <!-- 所属供应商链 -->
        <el-form-item label="所属供应商链：">
          <el-select v-model="formOption.data.supplyId" clearable placeholder="请选择所属供应商链">
            <el-option
              v-for="(item, index) in supplyList"
              :key="index"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 供应商 -->
        <el-form-item label="供应商：">
          <ScrollSelect
            placeholder="请选择供应商"
            :selected-value="formOption.data.supplierId"
            :get-list-methods="getListMethods"
            :get-list-format="getListFormat"
            :clearable="true"
            search-key="name"
            @selectedChange="selectedChange"
          />
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button @click="handleSearch" type="primary">筛选</el-button>
          <el-button @click="handleReload">重置</el-button>
          <el-button @click="handleExport">导出</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <Tabs :tabs="ORDER_SEARCH_STATUS" :currentKey="currentKey" @tab-click="tabClick">
      <div>
        <el-button @click="batchShip">批量发货</el-button>
        <el-button @click="exportFileByEmail" type="primary" :loading="allLoading"
          >导出全部</el-button
        >
      </div>
    </Tabs>

    <el-card class="mt-20">
      <OrderItemTabs :tabs="ORDER_LIST_COLUMNS" />
      <div v-if="orderList.length" class="order-list">
        <OrderItem
          v-for="(item, index) in orderList"
          :key="index"
          :order-item="item"
          @update="getOrderList"
        />
      </div>

      <Pagination
        v-show="total > 0"
        :total="total"
        :pageNo.sync="listQuery.pageNo"
        :pageSize.sync="listQuery.pageSize"
        @pagination="getOrderList"
      />
    </el-card>

    <el-empty v-if="!orderList.length" description="暂无数据" />

    <!-- 导出全部 -->
    <SelectEmail v-model="SelectEmailDialog" :type="exportType" @exportAll="handleExportAll" />
  </div>
</template>

<script>
import { headerData, filterData } from './exportOptions'
import { export2TreeExcel } from '@/utils/export'
import OrderItem from './components/OrderItem.vue'
import OrderItemTabs from './components/OrderItemTabs.vue'
import {
  ORDER_STATUS,
  ORDER_SEARCH_STATUS,
  ORDER_LIST_COLUMNS,
  ORDER_PLATFORM,
  ORDER_TYPE
} from '@/enum/order'
import { mapMutations, mapState, mapGetters } from 'vuex'
export default {
  name: 'OrderList',
  components: {
    OrderItem,
    OrderItemTabs
  },
  data() {
    return {
      formOption: {
        data: {
          status: '',
          orderSource: '',
          supplyId: '',
          platform: '',
          goodsName: '',
          expressNo: '',
          supplierId: ''
        },
        rules: {
          orderNo: [
            {
              pattern: /^[A-Za-z0-9]{1,30}$/,
              message: '仅支持字母和数字输入，限制30字符'
            }
          ]
        },
        items: [
          {
            type: 'input',
            label: '订单搜索',
            value: 'orderNo',
            placeholder: '请输入订单编号进行搜索',
            style: {
              width: '240px'
            }
          },
          {
            type: 'input',
            label: '快递单号',
            value: 'orderNo',
            placeholder: '请输入快递单号进行搜索',
            style: {
              width: '240px'
            }
          },
          {
            type: 'datetimerange',
            label: '下单时间',
            value: 'time',
            format: 'yyyy-MM-dd HH:mm',
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          },
          {
            type: 'select',
            label: '订单状态',
            value: 'status',
            style: {
              width: '210px'
            },
            selectList: ORDER_SEARCH_STATUS.filter(item => item.key !== 'addressUpdateNum')
          },
          {
            type: 'select',
            label: '订单类型',
            value: 'orderSource',
            style: {
              width: '210px'
            },
            selectList: ORDER_TYPE
          },
          {
            type: 'input',
            label: '客户信息',
            value: 'userInfo',
            placeholder: '请输入收货人姓名或者手机号',
            style: {
              width: '240px'
            }
          },
          {
            type: 'select',
            label: '所属供应链',
            value: 'supplyId',
            labelWidth: '100px',
            style: {
              width: '210px'
            },
            selectList: []
          },
          {
            type: 'select',
            label: '供应商',
            value: 'supplierId',
            labelWidth: '80px',
            style: {
              width: '210px'
            },
            selectList: []
          },
          {
            type: 'select',
            label: '下单平台',
            value: 'platform',
            style: {
              width: '210px'
            },
            selectList: ORDER_PLATFORM
          },
          {
            type: 'input',
            label: '商品名称',
            value: 'goodsName',
            placeholder: '请输入商品名称',
            style: {
              width: '240px'
            }
          }
        ]
      },

      listQuery: {
        pageNo: 1,
        pageSize: 10
      },
      total: 0,
      currentKey: 'totalNum',
      loading: false,
      // 导出全部加载
      allLoading: false,
      ORDER_SEARCH_STATUS: [],
      SelectEmailDialog: false,
      exportType: 16,

      // 获取供应商
      getListMethods: params => {
        return this.getSuplier(params)
      },

      // 选择开始时间大于等于当前时间
      // pickerOptions: {
      //   disabledDate(time) {
      //     const dateTime = new Date()
      //     const startDateTime = dateTime.setDate(dateTime.getDate() - 1)
      //     const endDateTime = dateTime.setDate(dateTime.getDate() + 30000) //30000为当前日期之后多少天
      //     return (
      //       time.getTime() < new Date(startDateTime).getTime() ||
      //       time.getTime() > new Date(endDateTime).getTime()
      //     )
      //   },
      //   selectableRange:
      //     //setMinutes,getMinutes限制分 , 年、月、日、时、分、秒同理,+1为数字区间
      //     parseTime(new Date().setMinutes(new Date().getMinutes() + 1), '{hh}:{ii}:{ss}') +
      //     '- 23:59:00'
      // },

      // 所属供应商链
      supplyList: []
    }
  },
  computed: {
    ...mapState('order', ['orderList']),
    ...mapGetters(['selectOrderList']),
    ORDER_LIST_COLUMNS() {
      return ORDER_LIST_COLUMNS
    },
    orderStatusList() {
      return ORDER_SEARCH_STATUS.filter(item => item.key !== 'addressUpdateNum')
    },
    ORDER_TYPE() {
      return ORDER_TYPE
    }
  },
  created() {
    this.getOrderTotal()
    this.getSupplyList()
    this.getSuplier()
    this.getOrderList()
  },
  activated() {
    this.getOrderTotal()
    this.getSupplyList()
    this.getSuplier()
    this.getOrderList()
  },
  methods: {
    ...mapMutations('order', ['SET_ORDER_LIST']),

    /**
     * @description 表单操作按钮
     * @handleSearch 搜索
     * @handleReload 重置
     * @handleExport 导出
     */

    handleSearch() {
      this.listQuery.pageNo = 1
      this.currentKey = ORDER_SEARCH_STATUS.find(
        item => item.value === this.formOption.data.status
      )?.key
      this.getOrderTotal()
      this.getOrderList()
    },
    handleReload() {
      this.formOption.data = {
        status: '',
        orderSource: '',
        supplyId: '',
        platform: '',
        expressNo: '',
        supplierId: ''
      }
      this.listQuery.pageNo = 1
      this.getOrderTotal()
      this.getOrderList()
    },
    handleExport() {
      this.exportFile()
    },

    tabClick({ key, value }) {
      this.currentKey = key
      // isSearchUpdateList
      if (key == 'addressUpdateNum') {
        this.formOption.data.status = ''
        this.formOption.data.isSearchUpdateList = true
      } else {
        this.formOption.data.isSearchUpdateList = false
        this.formOption.data.status = value
      }
      this.listQuery.pageNo = 1
      // this.getOrderTotal()
      this.getOrderList()
    },
    getPrams() {
      const params = {
        ...this.formOption.data,
        ...this.listQuery
      }
      const { status, time } = this.formOption.data
      if (time) params.startTime = time[0]
      if (time) params.endTime = time[1]
      if (status || status === 0) params.status = status
      delete params.time
      return params
    },
    // 获取订单列表
    async getOrderList() {
      this.loading = true
      const params = this.getPrams()
      const {
        data: { records, total }
      } = await this.$http.order.orderApi.getOrderList({ params })
      this.SET_ORDER_LIST({ key: 'orderList', data: records })
      // 获取统计
      this.total = total
      this.loading = false
    },

    // 获取订单统计
    async getOrderTotal() {
      const params = this.getPrams()
      const { data } = await this.$http.order.orderApi.getOrderTotal({ params })
      if (data) {
        this.ORDER_SEARCH_STATUS = ORDER_SEARCH_STATUS.map(item => {
          for (const key in data) {
            if (item.key === key) {
              item.num = data[key]
            }
          }
          return item
        })
      } else {
        this.ORDER_SEARCH_STATUS = ORDER_SEARCH_STATUS.map(item => {
          return { ...item, num: 0 }
        })
      }
    },

    // 获取所属供应链
    async getSupplyList() {
      const { data } = await this.$http.supply.getSupplyList()
      this.supplyList = data.map(el => ({
        ...el,
        value: el.id,
        label: el.name
      }))
    },

    // 获取供应商列表
    async getSuplier(params) {
      const { data } = await this.$http.goods.supplier.list({ params })
      return data
    },

    getListFormat: (list = []) => {
      // 下拉框数据格式
      return list.map(({ name, id }) => ({
        label: name,
        value: id
      }))
    },
    // 监听选择供应商信息
    selectedChange(id) {
      console.log(id, '------')
      this.formOption.data.supplierId = id
    },

    // 导出全部
    async exportFileByEmail() {
      this.$confirm(
        '确定要导出全部吗？数据量较大会导出较慢，请耐心等待。请勿重复点击，如出现导出失败，请联系技术部门。',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(async () => {
          this.SelectEmailDialog = true
        })
        .catch(err => err)
    },
    // 导出全部
    async handleExportAll(value) {
      const params = {
        email: value,
        ...this.formOption.data
      }

      const { status, time } = this.formOption.data
      if (time) params.startTime = time[0]
      if (time) params.endTime = time[1]
      if (status || status === 0) params.status = status
      delete params.time

      this.allLoading = true
      const res = await this.$http.order.orderApi.exportEmail({ params })
      if (res.status == 200) {
        this.allLoading = false
        this.$message.success('导出成功')
      }
    },
    // 批量发货
    batchShip() {
      this.$router.push({ name: 'BatchShip' })
    },
    // 订单状态
    orderStatusText(status, finishFlag) {
      if (status === 31 && finishFlag) {
        return '已完成'
      } else if (status === 31 && !finishFlag) {
        return '已评价'
      } else {
        return ORDER_STATUS[status]
      }
    },
    // 导出文件
    async exportFile() {
      if (!this.selectOrderList.length) return this.$message.error('请选择要导出的数据！')
      let arrnew = []
      const list = this.$lodash.cloneDeep(this.selectOrderList)
      list.map(item => {
        item.detailList.forEach(v => {
          arrnew.push({
            orderNo: item.orderNo,
            createdTime: item.createdTime,
            platform: ORDER_PLATFORM.find(val => val.value == item.platform)?.label,
            name: item.address.name,
            mobile: item.address.mobile,
            detail: `${item.address.provinceName}${item.address.cityName}${item.address.districtName}${item.address.detail}`,
            goodsSupply: v.supplierName,
            goodsName: v.goodsName,
            goodsPrice: v.goodsPrice,
            costPrice: v.costPrice,
            goodsNum: v.goodsNum,
            goodsRealityAmount: `${v.goodsRealityAmount}`,
            orderStatus: this.orderStatusText(item.orderStatus, item.finishFlag),
            payType: v.payType == 1 ? '积分' : '积分+运费',
            goodsSkuName: v.goodsSkuName,
            userRemark: item.userRemark,
            freightTotalAmount: item.freightTotalAmount,
            totalMoney: Number(item.freightTotalAmount) + Number(item.payAmount)
          })
        })
      })
      let goodsTitle_c = filterData.indexOf('orderStatus') //node的列下标,找最后一个
      let current_r = 1 //当前行从1开始（因为0是表头）
      let goodsTitle_s_r = 1 //node的开始行 从1开始

      let merges = []
      for (let i = 0; i < list.length; i++) {
        const element = list[i]
        for (let j = 0; j < element.detailList.length; j++) {
          current_r++
        }
        const fliter_list = [7, 8, 9, 10, 11]
        for (let c = 0; c < goodsTitle_c; c++) {
          if (goodsTitle_s_r !== current_r - 1 && !fliter_list.includes(c)) {
            //开始r ！= 结束行 则是合并
            let nodeMerges = {
              s: { c: c, r: goodsTitle_s_r },
              e: { c: c, r: current_r - 1 }
            }
            merges.push(nodeMerges)
          }
        }
        goodsTitle_s_r = current_r
      }
      export2TreeExcel(headerData, arrnew, filterData, '订单列表', merges, () => {
        this.$message.success('导出成功')
      })
    }
  }
}
</script>
